from typing import Optional

from aiogram_dialog import DialogManager
from fluentogram import TranslatorRunner

from src.core.models.enums.promocode import PromocodeType
from src.database.services.category import CategoryService
from src.database.services.order import OrderService
from src.database.services.product import ProductService
from src.database.services.promocode import PromocodeService
from src.database.services.user import UserService


async def user_orders_getter(dialog_manager: DialogManager, **kwargs):
    order_service: OrderService = dialog_manager.middleware_data.get("order_service")
    user_orders = await order_service.get_user_orders(dialog_manager.event.from_user.id)

    return {"user_orders": user_orders}


async def order_info_getter(dialog_manager: DialogManager, **kwargs):
    locale: TranslatorRunner = dialog_manager.middleware_data.get("locale")
    order_service: OrderService = dialog_manager.middleware_data.get("order_service")

    order_id: int = dialog_manager.dialog_data.get("order_id")
    order = await order_service.get_order_by_id(order_id)

    # Нужно для пополнения баланса из заказа
    dialog_manager.dialog_data["order_summ"] = order.summ

    return {
        "order_id": order.id,
        "order_summ": order.summ,
        "was_created": order.created_at,
    }


async def order_summary_getter(
    dialog_manager: DialogManager,
    user_service: UserService,
    category_service: CategoryService,
    product_service: ProductService,
    promocode_service: PromocodeService,
    **kwargs
):
    """Рассчитываем сумму заказа"""

    user_id: int = dialog_manager.event.from_user.id

    category_id: int = dialog_manager.dialog_data.get("category_id")
    category = await category_service.get_category_by_id(category_id)

    products_count: int = dialog_manager.dialog_data.get("selected_amount")
    products = await product_service.get_available_products(category_id, products_count)

    promocode = None
    promocode_id: Optional[int] = dialog_manager.dialog_data.get("promocode_id")
    if promocode_id:
        promocode = await promocode_service.get_promocode_by_id(promocode_id)

    user = await user_service.get_user_by_telegram_id(user_id)

    order_summ = category.price * len(products)

    discount_summ = None
    if promocode and promocode.type == PromocodeType.discount:
        # Уменьшаем сумму заказа при наличии промокода
        discount_summ = (order_summ / 100) * promocode.amount
        order_summ = order_summ - discount_summ
        dialog_manager.dialog_data["discount_summ"] = discount_summ

    dialog_manager.dialog_data["order_summ"] = order_summ

    return {
        "order_summ": order_summ,
        "discount_summ": discount_summ,
        "user_balance": user.balance,
    }
